<template>
  <div class="echarts" ref="chartRef" :style="style"></div>
</template>
<script setup>
import { ref, watch, onMounted, computed } from 'vue'
// import { chartColor } from '@/config'
import * as echarts from 'echarts'

const props = defineProps({
  options: { tpye: Object },
  height: { type: [Number, String] },
  noMerge: { type: Boolean, default: true },
})

let chart = null
const chartRef = ref(null)
const exposeChart = ref(null)

const style = computed(() => {
  const style = {
    width: '100%',
  }
  if (props.height) {
    const height = typeof props.height == 'number' ? props.height + 'px' : props.height
    style.height = height
  }
  return style
})

const initChart = () => {
  chart = echarts.init(chartRef.value)
  exposeChart.value = chart
  setOptions()
}

const setOptions = () => {
  const option = {
    // color: chartColor,
    ...props.options,
  }

  chart.setOption(option, props.noMerge)
}

//获取当前路由地址
watch(
  () => props.options,
  val => setOptions(),
  { deep: true }, //深度监听
)

onMounted(() => {
  initChart()
  window.addEventListener('resize', onResize)
})

onBeforeUnmount(() => {
  chart.clear()
  window.removeEventListener('resize', onResize)
})

defineExpose({
  chart: exposeChart,
})

const onResize = () => {
  chart.resize()
}
</script>
<style lang="scss" scoped>
.echarts {
  width: 100%;
  height: 100%;
}
</style>
